<?php
if (!class_exists('FacebookApiException')) {
    require_once 'facebook.php';
}
class AppController extends Controller {
	//var $uses = array('User');
	var $components = array(
		'Session', 
		'Auth', 
		'RequestHandler', 
		'Seo');
	var $uses = array('User', 'Setting', 'Fbprofile', 'Team', 'Product'); 
	var $helpers = array('Session', 'Form', 'Text');
	
	var $__fbApiKey = FB_API_KEY;
    var $__fbSecret = FB_SECRET_KEY;
    var $curFbUid = 0;
    var $fbErrorMsg_Session_key_invalid_or_no_longer_valid = false;
	
	function __construct() {
        parent::__construct();
        // Prevent the 'Undefined index: facebook_config' notice from being thrown. 
        $GLOBALS['facebook_config']['debug'] = NULL;
        // Create a Facebook client API object. 
        // $this->facebook = new Facebook($this->__fbApiKey, $this->__fbSecret); 
        $this->set('fbApiKey', $this->__fbApiKey);
    }
	
	function afterFilter(){
/*
		if($this->Auth->user())// track only if user login
		{
			$view['url'] = $this->here;

			
			if($this->Session->check('Auth.User.id'))
			{
				$view['user_id'] = $this->Session->read('Auth.User.id');
			}
			
			$view['ip'] = $_SERVER['REMOTE_ADDR'];
			
			$this->Pageview->save($view);
		}*/

	}
	
	function beforeFilter()
	{
		// Create our Application instance (replace this with your appId and secret).
		$this->facebook = new Facebook(array(
                    'appId' => FB_API_KEY,
                    'secret' => FB_SECRET_KEY
                ));
        $this->set('facebook', $this->facebook);
		// debug($this->facebook->api('me'));
		// debug($this->here);
		// debug($_SERVER['HTTP_HOST']);
		// debug($this->webroot);
		
		$this->set('user', $this->Auth->user());
		
		//2. retrieving session
		$session = $this->facebook->getUser();

		//3. requesting 'me' to API
		$fb_user = null;
		if ($session) {
		  try {
			$uid = $this->facebook->getUser();
			$fb_user = $this->facebook->api('/me');
		  } catch (FacebookApiException $e) {
			error_log($e);
		  }
		}

		//4. login or logout
		if ($fb_user) {
			$logoutUrl = $this->facebook->getLogoutUrl();
			$this->set('logoutUrl', $logoutUrl);
			// $this->Session->write('Facebook.logoutUrl',$logoutUrl);
			// debug($this->Session->read('Facebook.logoutUrl'));
		} else {
			$loginUrl = $this->facebook->getLoginUrl();
			$this->set('loginUrl', $loginUrl);
		}
		
		$this->set('facebook_user', $fb_user);

		if (!isset($fb_user['email']))
			$fb_user['email'] = $fb_user['link'];
		
		if (isset($fb_user['id']) && $fb_user['id'] > 0)
		{
			$user = $this->User->findByFacebookId($fb_user['id']);
			if($user){
				$this->Session->write("Auth.User", $user['User']);
			}
			else{
				$user_record['User']['facebook_id'] = $fb_user['id'];
				$user_record['User']['name'] = $fb_user['name'];
				$user_record['User']['username'] = $fb_user['email'];
				$user_record['User']['password'] = $this->Auth->password($fb_user['id']);
				$user_record['User']['email'] = $fb_user['email'];
				if(strcmp($fb_user['gender'], 'male') == 0){
					$user_record['User']['gender'] = MALE;
				}
				else{
					$user_record['User']['gender'] = FEMALE;
				}
				// $user['birthday'] = date("YY-mm-D", strtotime($fb_user['birthday']));
				$user_record['User']['avatar'] = 'http://graph.facebook.com/' . $fb_user['id'] . '/picture';
				$this->User->create();
				$this->User->save($user_record, array('validate' => false));
				$this->redirect('/');
			}
		}
		
		if(isset($this->params['prefix']))
		{
			$this->prefix= $this->params['prefix']; 
			if($this->prefix == 'admin')
			{
				$this->layout='admin_default';
					
			}
		}
		
		$this->Auth->loginRedirect = array('controller'=>'users', 'action'=>'view'); //can not be just "/" will cause redirection loop in cakephp login
		// $this->Auth->authorize = 'actions';
		$this->Auth->allow('*');
		
		// Update member count
		$this->User->member_count_update();
		
		$this->Auth->autoRedirect=false;
		if(isset($this->params['prefix']))
		{
		$this->prefix= $this->params['prefix']; 
		if($this->prefix == 'admin')
		{  
			if($this->Auth->user('role') !=ADMIN )//non-admin user
			{ 
				$this->redirect('/'); 
			}
		}
		}
	}
	
	function isAuthorized(){
		return true;
	}
	
	function last_login()
	{
		//-- code inside this function will execute only when autoRedirect was set to false (i.e. in a beforeFilter).
		if ($this->Auth->user()) {
			$curr_user_id = $this->Session->read('Auth.User.id');
			$currlogin = date('Y-m-d H:i:s');
			
	
			$this->User->id = $curr_user_id;
			$lastlogin = $this->User->field('lastlogin');
			
			// debug(strtotime($currlogin));
			// debug(strtotime($lastlogin));
			
			$timediff = strtotime($currlogin) - strtotime($lastlogin);
			
			// debug($timediff);
			// debug($timediff/3600);
			
			//$min_login_hour = 3;
			
			if( $timediff > UNIQUE_LOGIN_DURATION )
			{
				if($this->Session->check('Auth.User.id'))
				{
					$login['user_id'] = $this->Session->read('Auth.User.id');
				}

				$login['ip'] = $_SERVER['REMOTE_ADDR'];
				
				$this->Loginlog->save($login); 
			}

			
			$this->User->id = $curr_user_id;
			$this->User->saveField('lastlogin', $currlogin); //updating last_login field.

			$this->redirect($this->Auth->redirect());
		}
	}
	
	/*
	facebook connect
	1. check database if user info present
	2. if yes, log user in with cakephp auth
	3.if no, retrieve from facebook and store those info into database, and log user in with cakephp auth
	*/
	/* private function __checkFbUser()
	{ 
		//see if this facebook id is in the User database; if not, create the user using their fbid hashed as their password
		$user_record =
			$this->User->find('first', array(
				'conditions' => array('User.uid' => $this->curFbUid),
				'fields' => array('User.id, User.uid', 'User.username', 'User.password', 'User.role'),
				'contain' => array()
			));
		
		//create new user
		if(empty($user_record))
		{		
			try {
				$me = $this->facebook->api('/me');
				
				// $current_fb_profile = $this->User->findByUid($me['id']);
				// if((!$current_fb_profile) || count($current_fb_profile['User'])<1) 
				// {
					$affiliations = '';
					
					$profile['uid'] = $me['id'];
					$profile['name'] = $me['name'];
					$profile['first_name'] = $me['first_name'];
					$profile['last_name'] = $me['last_name'];
					$profile['birthday'] = $me['birthday'];
					$profile['gender'] = $me['gender'];
					$profile['timezone'] = $me['timezone'];
					$profile['locale'] = $me['locale'];
					$profile['verified'] = $me['verified'];
					$profile['email'] = $me['email'];
					$profile['username'] = $me['email'];//facebook loging need to fill in the user name and password, or else the auth won work
					//if user loging using cakephp auth with his password before, dun over write the paswrod with our predefined password fro user
					//if user never use cakephp auth to loging before, use default password as the value of "first_name"

					$profile['password'] = $this->Auth->password($me['email']);//facebook loging need to fill in the user name and password, or else the auth won work
					
					// save friend ids list
					$friends = $this->facebook->api('/me/friends');
					$friend_ids = array();
					foreach($friends['data'] as $friend)
					{
						$friend_ids[] = $friend['id'];
					}
					$profile['friend'] = implode(',', $friend_ids);	
					
					// suppress error, not a good way to do thing
					@$profile['location'] = $me['location']['name'];
					$profile['link'] = $me['link'];
					
					$this->data['User'] = $profile;
					$this->User->save($this->data);
					$this->Auth->login($this->data); //Login into our own auth after facebook login
					$this->last_login();//update user last loging datetime
					$current_fb_profile = $this->User->findByUid($me['id']);
				//}
				
				$this->set('current_fb_profile', $current_fb_profile); */
				
				
				
				
				
				
				/* $currentFbUser = $this->facebook->api('/me');	
				$user_record['fb_id'] = $this->curFbUid ; 
				$user_record['password'] = $this->Auth->password('fb');
				$user_record['gender'] = $currentFbUser['gender'];
				$user_record['first_name'] = $currentFbUser['first_name'];
				$user_record['last_name'] = $currentFbUser['last_name'];
				$user_record['username'] = $currentFbUser['email'];
				@$user_record['fb_location'] = $currentFbUser['location']['name'];
				$this->User->create();
				$this->User->save($user_record);
				$this->Auth->login($user_record);   */
				
			/* } 
			catch (FacebookApiException $e) 
			{
				debug($e.getResult());
			}

		}
		else
		{
			//log in the user with facebook credentials
			//with facebook connect
			
			$this->Auth->login($user_record); 
			$this->last_login();//update user last loging datetime
		}
	}	 */
	
	
	function beforeRender()
	{ 
		// add in meta data
		$url = $this->params['url']['url'];
		// Set the page meta
		$this->Seo->configureMeta($url);
		// $this->pageTitle = $this->Seo->getStr('page_title'); // does not work in cakephp 1.3
		$this->set('title_for_layout', $this->Seo->getStr('page_title'));
		$this->set('meta_title', $this->Seo->getStr('page_title'));
		$this->set('meta_keywords', $this->Seo->getStr('meta_keywords'));
		$this->set('meta_description', $this->Seo->getStr('meta_description'));
		
		// retrieve more thing from Config table
		$setting_list = $this->Setting->find('all');
		$settings = array();
		foreach($setting_list as $setting_line)
		{
			$settings[$setting_line['Setting']['key']] = $setting_line['Setting']['value'];
		}
		$this->set('settings', $settings);
	}
}
?>
